package com.dinadi.yidi.base;

import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;



import com.dinadi.yidi.R;
import com.dinadi.yidi.bean.CityModel;
import com.dinadi.yidi.bean.DistrictModel;
import com.dinadi.yidi.bean.ProvinceModel;
import com.dinadi.yidi.dialog.DialogControl;
import com.dinadi.yidi.dialog.DialogHelp;
import com.dinadi.yidi.dialog.MyProgressDialog;
import com.dinadi.yidi.utils.XmlParserHandler;
import com.dinadi.yidi.utils.app.AppManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import butterknife.ButterKnife;

public abstract class BaseActivity extends FragmentActivity implements DialogControl, View.OnClickListener {
    public boolean isTitle = true;
    private ProgressDialog _waitDialog;
    private boolean _isVisible;
    private MyProgressDialog _loadingDialog;
    public LoadingPage mLoadingPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        if (isTitle) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        mLoadingPage = new LoadingPage(getApplicationContext()) {


            @Override
            public View createSuccessView() {

                return getLayout();
            }


        };
        setContentView(mLoadingPage);
        // 通过注解绑定控件
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
        registerCommonBtn();
        PushAgent.getInstance(this).onAppStart();

    }

    /**
     * 改变显示的页面
     * public final int STATE_LOADING = 0;//加载中的状态
     * public final int STATE_ERROR = 1;//加载失败的状态
     * public final int STATE_SUCCESS = 2;//加载成功的状态
     */
    public void changePager(int state) {
        if (mLoadingPage != null) {
            mLoadingPage.mState = state;
            mLoadingPage.showPage();
        }
    }


    /**
     * 设置错误页的标题,图片等
     *
     * @param tv_error_title
     */
    public void setErTitle(String tv_error_title, int iv_error, boolean isHasBtn) {
        //   mLoadingPage.setErrorTitle(tv_error_title, iv_error, isHasBtn);
    }

    /**
     * 设置是否显示标题栏 true 显示 false 部显示
     */
    protected void setIsTitle(boolean isTitle) {
        this.isTitle = isTitle;
    }


    /**
     * 显示一个内容为msg的吐司
     */
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 显示一个内容为msgId引用的String的吐司
     */
    public void toast(int msgId) {
        Toast.makeText(this, msgId, Toast.LENGTH_SHORT).show();
    }


    /**
     * 加载框的显示和移除
     *
     * @param messege
     */
    public void showLoadingDialog(String messege) {
        if (_loadingDialog == null) {
            _loadingDialog = new MyProgressDialog(this, R.style.progress_dialog);
        }
        _loadingDialog.openProgressDialog(messege);
    }

    public void closeLoadingDialog() {
        if (_loadingDialog != null) {
            _loadingDialog.closeProgressDialog();
        }
    }

    //以下方法为网络请求时的等待框
    @Override
    public ProgressDialog showWaitDialog() {
        return showWaitDialog(R.string.loading);
    }

    @Override
    public ProgressDialog showWaitDialog(int resid) {
        return showWaitDialog(getString(resid));
    }

    @Override
    public ProgressDialog showWaitDialog(String message) {
        if (_isVisible) {
            if (_waitDialog == null) {
                _waitDialog = DialogHelp.getWaitDialog(this, message);
            }
            if (_waitDialog != null) {
                _waitDialog.setMessage(message);
                _waitDialog.show();
            }
            return _waitDialog;
        }
        return null;
    }

    @Override
    public void hideWaitDialog() {
        if (_isVisible && _waitDialog != null) {
            try {
                _waitDialog.dismiss();
                _waitDialog = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 在多个界面间公用的按钮，在此处注册点击事件
     */
    private void registerCommonBtn() {
        //返回按钮
        View view = findViewById(R.id.title_back);
        //lodding 返回按钮

        if (view != null) {
            view.setOnClickListener(this);

        }
        //重新加载按钮
        ImageView bt_error = (ImageView) findViewById(R.id.btn_reload);
//        TextView bt_error = (TextView)findViewById(R.id.bt_error);

        if (bt_error != null) {
            bt_error.setOnClickListener(this);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                super.finish();
                break;
            case R.id.btn_reload:
                //网络错误的按钮，重新进行数据的请求

                noWifiRefresh();
                break;
            default:
                clickEvent(view);
                break;
        }

    }

    /**
     * 返回当前Activity使用的布局对象
     */
    protected abstract View getLayout();

    /**
     * 没有网络的情况下显示没有网络的界面，点击重新刷新
     */
    protected abstract void noWifiRefresh();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化监听
     */
    protected abstract void initListener();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 点击事件的监听
     *
     * @param v
     */
    protected abstract void clickEvent(View v);


    protected void registerClickListener(View... views) {
        for (View v : views) {
            v.setOnClickListener(this);
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName = "";
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName = "";
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode = "";

    /**
     * 解析省市区的XML数据
     */
    protected void initProvinceDatas() {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
// 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
// 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
// 获取解析出来的数据
            provinceList = handler.getDataList();
//*/ 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
//*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
// 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
// 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
// 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
// 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
// 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
// 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }

}
